# encoding:utf-8
from __future__ import unicode_literals
from django.http import HttpResponse
from django.conf import settings
import json
import time
from models import OrderModel
import base64
from helpers.wechat.pay import WXPay
from models import MealModel,CustomerModel,User,WXOrderModel,UserCarModel
import xmltodict
from django.db import transaction

class JSApiWXPay(WXPay):

    APPID=settings.WXPAY_MP_APPID
    APPSECRET=settings.WXPAY_MP_APPSECRET
    MACHID=settings.WXPAY_MP_MACHID
    APISECERT=settings.WXPAY_MP_APISECERT
    
    def fetch_order_args(self, resp):
        """
        从微信返回参数中提取 参数给前端，jsapi用
        """
        #resp['code'] = 1
        #resp['msg'] = resp.get('return_msg')      
        #resp['ret'] = (resp.get('return_code') == 'SUCCESS' and 1) or 0
        ret={
            'msg':resp.get('return_msg'),
             }
        
        if resp.get('return_code')!='SUCCESS':
            order_args={}
        else:
            order_args={
                'appId' : self.APPID,
                'package' : 'prepay_id=%s'%resp.get('prepay_id'),
                'nonceStr' : self.get_nonce_str(),
                'timeStamp' : str(int(time.time())),
                'signType':'MD5',
            }
            order_args['paySign']=self.params_sign(order_args)
        ret['order_args'] = order_args        
        return ret
    
  
    def makesure_order(self,data):
        """
        微信服务器确认订单支付后，会调用到这个函数
        
        微信可能同时多次通知，为了避免创建多个order，所以加上.原子锁
        """
        no=data.get('out_trade_no')
        with transaction.atomic():
            wxorder = WXOrderModel.objects.select_for_update().get(no=no)
            if wxorder.order:
                # 已经生成了内部订单，表示微信已经返回过结果了
                return 
            wxorder.transaction_id=data.get('transaction_id')
            wxorder.time_end=data.get('time_end')
            #wxorder.total_fee=data.get('total_fee')
            wxorder.openid=data.get('openid')
            wxorder.trade_type=data.get('trade_type')
            wxorder.result_code=data.get('result_code')
            
            if data.get('result_code')=='SUCCESS':
                # get_or_create 是原子操作
                # 避免由于异步问题，造成创建多个order的情况
                
                if wxorder.total_fee <= data.get('total_fee') :
                    wxorder.pay='payed'
                    #cus = CustomerModel.get_or_add(openid=wxorder.openid)
                    order=OrderModel.objects.create()
                    order.meal=wxorder.meal
                    order.price=wxorder.total_fee
                    order.car=wxorder.car
                    #order.user=cus.user
                    order.status='active'
                    order.save()
                    wxorder.order=order
                else:
                    wxorder.pay='no_enogh_mony'
                
            wxorder.save()
        
    def make_param(self,ip,openid,meal,coupon=None,chepai=None):
        """
        微信统一下单
        
        params = {
            'appid' : setting.WXPAY_APPID,
            'mch_id' : setting.WXPAY_MACHID,
            'device_info' : 'WEB',
            'nonce_str' : str(int(time.time())),
            'body' : self.meal['meal_name'],
            'detail': self.meal['meal_desc'],
            'out_trade_no' : self.orderno,
            'fee_type' : 'CNY',
            'total_fee' : int(float(self.meal['meal_nowprice'])*100),
            'spbill_create_ip' : (self.request_ip and self.request_ip) or '127.0.0.1',
            'notify_url' : setting.WXPAY_NOTIFY,
            'trade_type' : 'APP'
        }
        """ 
        # if not coupon:
            # total_fee=int(meal.price)
        # else:
            # total_fee=max(0, int(meal.price)-int(coupon.value))
        # meal_name=request.GET.get('meal')
        # meal = MealModel.objects.get(name=meal_name)
        # openid=request.GET.get('openid')
        # user = User.objects.get(customermodel__openid=openid)
        if chepai:
            car= UserCarModel.objects.get(car_no=chepai)
        else:
            car=UserCarModel.objects.get(user__customermodel__openid=openid)
        wxorder = WXOrderModel.objects.create(car=car)
        wxorder.meal=meal
        if coupon:
            wxorder.coupon=coupon
            total_fee=max(0,int(meal.price)-int(coupon.value))
        else:
            total_fee=meal.price
        wxorder.org_fee=meal.org_price
        wxorder.total_fee=total_fee
        wxorder.save()        
        
        param={
            'appid':self.APPID,
            'mch_id':self.MACHID,
            'device_info' : 'WEB',
            'nonce_str':self.get_nonce_str(),
            'body':meal.label,
            'detail':meal.detail,
            'out_trade_no':wxorder.no,
            'fee_type':'CNY',
            'total_fee' : wxorder.total_fee,
            'spbill_create_ip' : ip,
            'notify_url':settings.WX_PAY_NOTIFY_URL,
            'trade_type':'JSAPI',
            'openid':openid,
        }
        return param
    
    def reply(self,request):
        """"""
        notify_data = xmltodict.parse( request.body).get('xml')
        sign=notify_data.pop('sign')
        local_sign=self.params_sign(notify_data)
        ret={
            'return_code':'FAIL',
            'return_msg':'参数错误或缺少参数！'
        }
        if local_sign!=sign:
            ret={
                'return_code':'FAIL',
                'return_msg':'签名失败'
            }            
        elif notify_data.get('return_code')=='SUCCESS':
            self.makesure_order(notify_data)
            ret={
                'return_code':'SUCCESS',
                'return_msg':'OK'
            }
        xml_str='<xml>'
        for k,v in ret.items():
            xml_str+='<{key}><![CDATA[{value}]]></{key}>'.format(key=k,value=v)
        xml_str+='</xml>'
        return xml_str
        #from xml.dom import minidom
        #code = 'FAIL'
        #msg = 'OK'
        #print notify_data
        #doc = minidom.parseString(notify_data)
        #root = doc.documentElement
        #return_code = self.gettagname_value(root,'return_code')
        #if return_code == 'SUCCESS':
            #result_code = self.gettagname_value(root,'result_code')
            #if result_code == 'SUCCESS':
                #orderid = self.gettagname_value(root,'out_trade_no')
                #res = self.updateorderstatus(orderid)
                #print res
                #if res==1:
                    #code= 'SUCCESS'
                #elif res == -1:
                    #code = 'FAIL'
                    #msg = '订单异常'
                #else:
                    #msg ='服务器处理失败，请稍后重试' 
            #else:
                #msg = '参数错误或缺少参数！'
        #else:
            #msg = '签名失败'
    
        #resp_return_tpl = '''
                #<xml>
                    #<return_code><![CDATA[%s]]></return_code>
                    #<return_msg><![CDATA[%s]]></return_msg>
                #</xml>
            #'''
        #resp_return = resp_return_tpl % (code,msg)
        #logger.info('wx_pay_notify:%s %s', code, msg)
        #self.set_header('Content-Type','text/xml')
        #self.write(resp_return)
        #self.finish()        
    
    
    
def get_order(request):
   
    timestamp=str(int(time.time()))
    dc= {"msg": "OK", 
         "code": 1, 
         "data": {"package": "Sign=WXPay", "timestamp": timestamp, 
                  "sign": "266750137C30A658F096E34B0AC5FF76", 
                  "partnerid": "1319446301", 
                  "appid": "wxb06d258b913888bf", 
                  "prepayid": "wx201611300908426ffa941e6e0638589474", 
                  "noncestr": "1480468122"}, 
         "ret": 1}
    
    dc={
        'msg':'this api has not use'
    }
    return HttpResponse(json.dumps(dc),content_type="application/json")



